package com.calvin.study.threadsafe.lock.viewlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class SpinLock implements Lock {

	private AtomicReference<Thread> owner = new AtomicReference<Thread>();

	@Override
	public void lock() {
		Thread t = Thread.currentThread();
		while (!owner.compareAndSet(null, t)) {
			Thread.yield();
		}

	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean tryLock() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void unlock() {
		Thread t = Thread.currentThread();
		// 只有拥有者才能释放锁
		if (t == owner.get()) {
			// 设置拥有者为空， 这里不需要 compareAndSet操作
			// 因为已经通过owner做过线程检查
			owner.set(null);
		}

	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}
